<!-- 人员选择下拉框组件 - 支持分页和搜索 -->
<template>
  <div class="art-employee-select">
    <ElSelect
      v-model="selectedValue"
      :multiple="multiple"
      :filterable="filterable"
      :remote="remote"
      :reserve-keyword="reserveKeyword"
      :remote-method="handleSearch"
      :loading="loading"
      :placeholder="placeholder"
      :clearable="clearable"
      :disabled="disabled"
      :collapse-tags="collapseTags"
      :collapse-tags-tooltip="collapseTagsTooltip"
      :max-collapse-tags="maxCollapseTags"
      :size="size"
      v-bind="$attrs"
      @visible-change="handleVisibleChange"
      @change="handleChange"
      @clear="handleClear"
    >
      <template #header>
        <div class="employee-select-header">
          <ElInput
            v-model="searchKeyword"
            :placeholder="searchPlaceholder"
            clearable
            @input="handleSearchInput"
            @keyup.enter="handleSearchEnter"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </ElInput>
        </div>
      </template>

      <ElOption
        v-for="employee in employeeList"
        :key="employee.id"
        :label="employee.employeeName"
        :value="employee.id!"
      >
        <div class="employee-option">
          <span class="employee-name">{{ employee.employeeName }}</span>
          <span class="employee-info">
            <template v-if="showLoginName && employee.loginName">
              <span> | </span>
              {{ employee.loginName }}
            </template>
            <template v-if="showPhone && employee.employeePhone">
              <span> | </span>
              {{ employee.employeePhone }}
            </template>
          </span>
        </div>
      </ElOption>

      <template #footer>
        <div class="employee-select-footer" style="display: flex;justify-content: space-between;align-items: center;">
          <div class="pagination-info">
            共 {{ totalCount }} 条
          </div>
          <div class="pagination-controls">
            <ElButton
              :disabled="currentPage <= 1"
              :icon="ArrowLeft"
              size="small"
              text
              @click="handlePrevPage"
            >
              上一页
            </ElButton>
            <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
            <ElButton
              :disabled="currentPage >= totalPages"
              :icon="ArrowRight"
              size="small"
              text
              @click="handleNextPage"
            >
              下一页
            </ElButton>
          </div>
        </div>
      </template>
    </ElSelect>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { ElSelect, ElOption, ElInput, ElButton } from 'element-plus'
  import { Search, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
  import { apiEmployeeGetPageUsingPost, type ApiEmployee } from '@/api'

  interface Props {
    /** 绑定值 */
    modelValue?: number | number[] | null
    /** 是否多选 */
    multiple?: boolean
    /** 是否可搜索 */
    filterable?: boolean
    /** 是否远程搜索 */
    remote?: boolean
    /** 保留关键字 */
    reserveKeyword?: boolean
    /** 占位符 */
    placeholder?: string
    /** 搜索框占位符 */
    searchPlaceholder?: string
    /** 是否可清空 */
    clearable?: boolean
    /** 是否禁用 */
    disabled?: boolean
    /** 每页条数 */
    pageSize?: number
    /** 启用禁用1启用0禁用 */
    disabledFlag?: number
    /** 是否显示登录账号 */
    showLoginName?: boolean
    /** 是否显示手机号 */
    showPhone?: boolean
    /** 是否折叠标签 */
    collapseTags?: boolean
    /** 折叠标签提示 */
    collapseTagsTooltip?: boolean
    /** 最大折叠标签数 */
    maxCollapseTags?: number
    /** 尺寸 */
    size?: 'large' | 'default' | 'small'
    /** 部门ID筛选 */
    deptId?: number
  }

  interface Emits {
    (e: 'update:modelValue', value: number | number[] | null): void
    (e: 'change', value: number | number[] | null): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: null,
    multiple: false,
    filterable: true,
    remote: true,
    reserveKeyword: true,
    placeholder: '请选择人员',
    searchPlaceholder: '输入姓名或账号搜索',
    clearable: true,
    disabled: false,
    pageSize: 10,
    disabledFlag: 1,
    showLoginName: true,
    showPhone: false,
    collapseTags: false,
    collapseTagsTooltip: true,
    maxCollapseTags: 1,
    size: 'default'
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const employeeList = ref<ApiEmployee[]>([])
  const loading = ref(false)
  const searchKeyword = ref('')
  const currentPage = ref(1)
  const totalCount = ref(0)

  // 计算总页数
  const totalPages = computed(() => {
    return Math.max(1, Math.ceil(totalCount.value / props.pageSize))
  })

  // 双向绑定值
  const selectedValue = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 获取员工列表
   */
  const getEmployeeList = async (keyword: string = '', page: number = 1) => {
    try {
      loading.value = true
      const res = await apiEmployeeGetPageUsingPost({
        body: {
          current: page,
          size: props.pageSize,
          disabledFlag: props.disabledFlag || 1,
          employeeName: keyword || undefined,
          deptId: props.deptId
        }
      })

      const pageData = res && res
      if (pageData.total > 0) {
        employeeList.value = pageData.list
        totalCount.value = pageData.total || 0
        currentPage.value = page
      }
    } catch (error) {
      console.error('获取员工列表失败:', error)
      employeeList.value = []
      totalCount.value = 0
    } finally {
      loading.value = false
    }
  }

  /**
   * 处理搜索输入
   */
  const handleSearchInput = (value: string) => {
    // 输入时不立即搜索，等待用户回车或点击搜索按钮
    searchKeyword.value = value
  }

  /**
   * 处理搜索回车
   */
  const handleSearchEnter = () => {
    currentPage.value = 1
    getEmployeeList(searchKeyword.value, 1)
  }

  /**
   * 处理远程搜索（由 ElSelect 触发）
   */
  const handleSearch = (query: string) => {
    searchKeyword.value = query
    currentPage.value = 1
    getEmployeeList(query, 1)
  }

  /**
   * 下拉框显示/隐藏
   */
  const handleVisibleChange = (visible: boolean) => {
    if (visible && employeeList.value.length === 0) {
      // 首次打开时加载数据
      getEmployeeList('', 1)
    }
  }

  /**
   * 上一页
   */
  const handlePrevPage = () => {
    if (currentPage.value > 1) {
      getEmployeeList(searchKeyword.value, currentPage.value - 1)
    }
  }

  /**
   * 下一页
   */
  const handleNextPage = () => {
    if (currentPage.value < totalPages.value) {
      getEmployeeList(searchKeyword.value, currentPage.value + 1)
    }
  }

  /**
   * 值变化
   */
  const handleChange = (value: number | number[] | null) => {
    emit('change', value)
  }

  /**
   * 清空
   */
  const handleClear = () => {
    emit('update:modelValue', null)
    emit('change', null)
  }

  // 监听部门ID变化，重新加载数据
  watch(
    () => props.deptId,
    () => {
      if (employeeList.value.length > 0) {
        currentPage.value = 1
        searchKeyword.value = ''
        getEmployeeList('', 1)
      }
    }
  )

  // 暴露方法供外部调用
  defineExpose({
    refresh: () => getEmployeeList(searchKeyword.value, currentPage.value),
    reset: () => {
      searchKeyword.value = ''
      currentPage.value = 1
      getEmployeeList('', 1)
    }
  })
</script>

<style lang="scss" scoped>
  .art-employee-select {
    width: 100%;

    :deep(.el-select) {
      width: 100%;
    }

    // 头部搜索区域
    .employee-select-header {
      padding: 8px 12px;
      border-bottom: 1px solid var(--el-border-color-light);

      .el-input {
        width: 100%;
      }
    }

    // 员工选项样式
    .employee-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      gap: 12px;

      .employee-name {
        font-weight: 500;
        color: var(--el-text-color-primary);
        flex-shrink: 0;
      }

      .employee-info {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    // 底部分页区域
    .employee-select-footer {
      width: 100%;
      border-top: 1px solid var(--el-border-color-light);
      background-color: var(--el-fill-color-blank);

      .pagination-info {
        width: 10%;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }

      .pagination-controls {
        width: 90%;
        display: flex;
        align-items: center;
        gap: 8px;

        .page-info {
          font-size: 12px;
          color: var(--el-text-color-regular);
          min-width: 50px;
          text-align: center;
        }

        :deep(.el-button) {
          padding: 4px 8px;
          
          &:disabled {
            opacity: 0.5;
          }
        }
      }
    }

    // 选项悬停效果
    :deep(.el-select-dropdown__item) {
      padding: 8px 12px;

      &:hover {
        background-color: var(--el-fill-color-light);
      }
    }
  }
  :deep(.employee-select-footer) {
    display: flex;
  }
</style>
